package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.JsonResult;
import cn.itsource.basic.util.LoginInfoUtil;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.pojo.Do.LoginDo;
import cn.itsource.org.pojo.loginInfo.LoginInfo;
import cn.itsource.org.pojo.vo.LoginVo;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl extends BaseServiceImpl<Employee,EmployeeQuery> implements IEmployeeService {

    /**
     * 注入mapper
     */
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private RedisService redisService;


    @Override
    public List<Employee> findManager() {
        return employeeMapper.findManager();
    }

    @Override
    public JsonResult LoginVerify(LoginDo loginDo) {
        //查用户
        String username = loginDo.getUsername();
        Employee dbEmployee = employeeMapper.selectUsername(username);
        //比对用户
        if(dbEmployee==null){
            throw new BusinessException("用户不存在");
        }
        //准备比对密码
        //获取老盐
        String salt = dbEmployee.getSalt();
        //对前端密码加密
        String pwd = MD5.create().setSalt(salt.getBytes()).digestHex(loginDo.getPassword());
        log.info("密码:{}",pwd);
        if(!StringUtils.equals(pwd,dbEmployee.getPassword())){
            throw new BusinessException("用户或者密码错误");
        }
        //准备春token
        String token = IdUtil.fastSimpleUUID();
        //存储数据
        //烤呗的时候有
        LoginInfo loginInfo = BeanUtil.copyProperties(dbEmployee, LoginInfo.class);
//        loginInfo.setShopId(dbEmployee.getShopId());
        redisService.setStringKeyAndValue(token,loginInfo,30);
        LoginVo loginVo = BeanUtil.copyProperties(dbEmployee, LoginVo.class);
        loginVo.setToken(token);
        //存公共的logininfo


        return JsonResult.createSuccess(loginVo);
    }

    @Override
    public List<Employee> findShopAllEmployee() {
        Long shopId = LoginInfoUtil.getShopId();
        //商店员工
        return employeeMapper.findShopAllEmployee(shopId);
    }


}